package sixth.group.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sixth.group.domain.Customer;
import sixth.group.domain.Logs;
import sixth.group.service.CustomerService;
import sixth.group.service.LogsService;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;
   @Autowired
   private LogsService logsService;
    @RequestMapping(value = "/register")
    @ResponseBody
    public void registerCusomer(Customer customer, HttpServletResponse response, HttpServletRequest request, HttpSession httpSession,String file) throws IOException {
        customer.setCbalance(0);
        //if(file.isEmpty())out.println("<script type='text/javascript'>alert('请选择您的头像！');window.location.href='../customerregister.jsp'</script>");
        boolean b = customerService.register(customer);
        PrintWriter out=response.getWriter();

        if(b) {
            //图片处理逻辑
             String fileName= file;//.getOriginalFilename();
            String path = request.getSession().getServletContext().getRealPath("images") + "\\" + fileName;

            System.out.println("图片存储在"+path);

//            try {
//                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
           customerService.insertimage(customer,"images/"+fileName);
            Customer integercustomer=customerService.findbyname(customer.getCusername());
            Logs log=new Logs();
            log.setLrole(2);
            log.setLusername(integercustomer.getCusername());
            log.setLoperation("新顾客注册");
            log.setLtype("注册");
            log.setLuptime(integercustomer.getCuptime());

          boolean logb= logsService.addLog(log);
          if(!logb)System.out.println("记入日志表失败");


            httpSession.setAttribute("Customer",integercustomer);
            out.println("<script type='text/javascript'>alert('Success!');window.location.href='../home.jsp'</script>");
        }
        else out.println("<script type='text/javascript'>alert('Failed!The same name or phone one already exists!');window.location.href='../customerregister.jsp'</script>");
    }

    @RequestMapping(value = "/modify")
    @ResponseBody
    public void modifyCustomer(Customer customer, HttpServletResponse response, HttpSession httpSession,String file) throws IOException {
        Date date=new Date(System.currentTimeMillis());
        customer.setCuptime(date);
        Customer sessioncustomer =(Customer) httpSession.getAttribute("Customer");
        if(file.equals("")){
            file=sessioncustomer.getCimage();
            customer.setCimage(file);
        }
        else customer.setCimage("images/"+file);
        //更新信息
        boolean b=customerService.modify(customer);
        PrintWriter out = response.getWriter();
        if(b) {
            Logs log=new Logs();
            log.setLrole(2);
            log.setLusername(customer.getCusername());
            log.setLoperation("修改了个人信息");
            log.setLtype("修改");
            log.setLuptime(customer.getCuptime());

            boolean logb= logsService.addLog(log);
            if(!logb)System.out.println("记入日志表失败");


            httpSession.setAttribute("Customer", customer);
            out.println("<script type='text/javascript'>alert('Success!');window.location.href='../home.jsp'</script>");
        }
        else out.println("<script type='text/javascript'>alert('Failed!The same name or phone one already exists!');window.location.href='../home.jsp'</script>");
    }




    @RequestMapping(value = "/login")
    public void loginCustomer(Customer customer, HttpSession httpSession,HttpServletResponse response,String code) throws IOException {
        PrintWriter out = response.getWriter();
        //调用service进行登录验证
        boolean status  = customerService.loginCheck(customer);

        if (!code.equals("nmdz")){
            out.println("<script type='text/javascript'>alert('Code is Wrong!');window.location.href='../customerlogin.jsp'</script>");
        }
        else {
            if (status) {
                //登录验证成功
                Customer customer1=customerService.findbyname(customer.getCusername());
                Logs log=new Logs();
                log.setLrole(2);
                log.setLusername(customer1.getCusername());
                log.setLoperation("登录进了饿了否");
                log.setLtype("登录");
                log.setLuptime(customer1.getCuptime());

                boolean logb= logsService.addLog(log);
                if(!logb)System.out.println("记入日志表失败");
                //http是一个无状态协议，为了保持通信双方的身份识别，一般采用  session（cookie）
                Customer integercustomer = customerService.findbyname(customer.getCusername());


                httpSession.setAttribute("Customer", integercustomer);
                if(integercustomer.getCpermission()==0)out.println("<script type='text/javascript'>alert('You have not perimission to enter!');window.location.href='../customerlogin.jsp'</script>");
                else out.println("<script>window.location.href='../home.jsp'</script>");
            } else {
                out.println("<script type='text/javascript'>alert('Username or Password is Wrong!');window.location.href='../customerlogin.jsp'</script>");
            }
        }
    }



}
